package com.management.department.teacherinfosystem.Controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.management.department.teacherinfosystem.DTO.AcademicAchievementSubmitDTO;
import com.management.department.teacherinfosystem.DTO.AcademicAchievementDTO;
import com.management.department.teacherinfosystem.Entity.AcademicAchievement;
import com.management.department.teacherinfosystem.Service.AcademicAchievementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/academic-achievements")
public class AcademicAchievementController {
    
    @Autowired
    private AcademicAchievementService achievementService;
    
    // 创建学术成果
    @PostMapping
    public ResponseEntity<?> createAchievement(
            @RequestPart("data") String data,
            @RequestPart(value = "files", required = false) MultipartFile[] files
    ) {
        try {
            // 解析JSON数据
            ObjectMapper mapper = new ObjectMapper();
            AcademicAchievementSubmitDTO dto = mapper.readValue(data, AcademicAchievementSubmitDTO.class);
            
            // 获取当前用户ID
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Long userId = getCurrentUserId(auth);
            dto.setCreatedBy(userId);
            
            AcademicAchievement achievement = achievementService.createAchievement(dto, files);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "学术成果提交成功");
            response.put("id", achievement.getId());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("提交失败：" + e.getMessage());
        }
    }
    
    // 创建学术成果（JSON格式，无文件）
    @PostMapping("/json")
    public ResponseEntity<?> createAchievementJson(@RequestBody AcademicAchievementSubmitDTO dto) {
        try {
            // 获取当前用户ID
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Long userId = getCurrentUserId(auth);
            if (userId == null) {
                return ResponseEntity.badRequest().body("提交失败：无法获取用户信息");
            }
            dto.setCreatedBy(userId);
            
            AcademicAchievement achievement = achievementService.createAchievement(dto, null);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "学术成果提交成功");
            response.put("id", achievement.getId());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("提交失败：" + e.getMessage());
        }
    }
    
    // 更新学术成果
    @PutMapping("/{id}")
    public ResponseEntity<?> updateAchievement(
            @PathVariable("id") Long id,
            @RequestPart("data") String data,
            @RequestPart(value = "files", required = false) MultipartFile[] files
    ) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            AcademicAchievementSubmitDTO dto = mapper.readValue(data, AcademicAchievementSubmitDTO.class);
            
            AcademicAchievement achievement = achievementService.updateAchievement(id, dto, files);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "学术成果更新成功");
            response.put("id", achievement.getId());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }
    
    // 更新学术成果（JSON格式，无文件）
    @PutMapping("/{id}/json")
    public ResponseEntity<?> updateAchievementJson(
            @PathVariable("id") Long id,
            @RequestBody AcademicAchievementSubmitDTO dto
    ) {
        try {
            // 获取当前用户ID
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Long userId = getCurrentUserId(auth);
            dto.setCreatedBy(userId);
            
            AcademicAchievement achievement = achievementService.updateAchievement(id, dto, null);
            
            Map<String, Object> response = new HashMap<>();
            response.put("message", "学术成果更新成功，已重新提交审核");
            response.put("id", achievement.getId());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }
    
    // 删除学术成果
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteAchievement(@PathVariable("id") Long id) {
        try {
            achievementService.deleteAchievement(id);
            return ResponseEntity.ok("删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败：" + e.getMessage());
        }
    }
    
    // 获取学术成果详情
    @GetMapping("/{id}")
    public ResponseEntity<?> getAchievement(@PathVariable("id") Long id) {
        try {
            AcademicAchievementDTO achievement = achievementService.getAchievementDTOById(id);
            if (achievement == null) {
                return ResponseEntity.notFound().build();
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("achievement", achievement);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取失败：" + e.getMessage());
        }
    }
    
    // 获取我的学术成果
    @GetMapping("/my")
    public ResponseEntity<?> getMyAchievements(@RequestParam("userId") Long userId) {
        try {
            List<AcademicAchievementDTO> achievements = achievementService.getMyAchievementsDTO(userId);
            return ResponseEntity.ok(achievements);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取失败：" + e.getMessage());
        }
    }
    
    // 获取所有学术成果（管理员）
    @GetMapping("/all")
    public ResponseEntity<?> getAllAchievements() {
        try {
            List<AcademicAchievementDTO> achievements = achievementService.getAllAchievementsDTO();
            return ResponseEntity.ok(achievements);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取失败：" + e.getMessage());
        }
    }
    
    // 获取教师列表（用于筛选）
    @GetMapping("/teachers")
    public ResponseEntity<?> getTeachers() {
        try {
            List<Map<String, Object>> teachers = achievementService.getTeachersList();
            return ResponseEntity.ok(teachers);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取失败：" + e.getMessage());
        }
    }
    
    // 根据作者姓名搜索成果ID列表
    @GetMapping("/search-by-author")
    public ResponseEntity<?> searchByAuthorName(@RequestParam("authorName") String authorName) {
        try {
            List<Long> achievementIds = achievementService.getAchievementIdsByAuthorName(authorName);
            return ResponseEntity.ok(achievementIds);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("搜索失败：" + e.getMessage());
        }
    }
    
    // 获取待审核的学术成果
    @GetMapping("/pending")
    public ResponseEntity<?> getPendingAchievements() {
        try {
            List<AcademicAchievementDTO> achievements = achievementService.getPendingAchievementsDTO();
            return ResponseEntity.ok(achievements);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取失败：" + e.getMessage());
        }
    }
    
    // 审核学术成果
    @PostMapping("/{id}/review")
    public ResponseEntity<?> reviewAchievement(
            @PathVariable("id") Long id,
            @RequestBody Map<String, Object> payload
    ) {
        try {
            String status = (String) payload.get("status");
            String opinion = (String) payload.get("opinion");
            
            // 获取当前审核人ID
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            Long reviewerId = getCurrentUserId(auth);
            
            achievementService.reviewAchievement(id, status, opinion, reviewerId);
            
            return ResponseEntity.ok("审核完成");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("审核失败：" + e.getMessage());
        }
    }
    
    // 上传附件
    @PostMapping("/{id}/attachments")
    public ResponseEntity<?> uploadAttachment(
            @PathVariable("id") Long id,
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "fileType", defaultValue = "证明材料") String fileType
    ) {
        try {
            achievementService.uploadAttachment(id, file, fileType);
            return ResponseEntity.ok("附件上传成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("上传失败：" + e.getMessage());
        }
    }
    
    // 删除附件
    @DeleteMapping("/attachments/{attachmentId}")
    public ResponseEntity<?> deleteAttachment(@PathVariable("attachmentId") Long attachmentId) {
        try {
            achievementService.deleteAttachment(attachmentId);
            return ResponseEntity.ok("附件删除成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败：" + e.getMessage());
        }
    }
    
    // 获取当前用户ID
    private Long getCurrentUserId(Authentication auth) {
        if (auth != null && auth.isAuthenticated()) {
            try {
                // 尝试从Principal中获取用户ID
                String username = auth.getName();
                System.out.println("当前登录用户名: " + username); // 添加调试日志
                if ("admin".equals(username)) {
                    return 1L;
                } else if ("t001".equals(username)) {
                    return 2L;
                } else if ("t002".equals(username)) {
                    return 3L;
                } else {
                    // 如果是其他用户名，记录日志并返回null
                    System.out.println("未知用户名: " + username);
                    return null;
                }
            } catch (Exception e) {
                System.out.println("获取用户ID失败: " + e.getMessage());
                return null;
            }
        }
        return null;
    }
}
